import * as $ from 'jquery';
import storage from './storage';
import SysData from './sysData';
// import * as swal from 'sweetalert';
//import {Md5} from 'ts-md5/dist/md5';

class Tools {
  //正则表达式
 REGPATTERN = {
   //特殊字符
   SPECIA_REG:'[^"\'<>%;)(&+}{#;=$]+',//'[^`~!@#$^&*=|{}\':;\',\\\\[\\\\].<>/?~@#￥……&*——|{}【】‘；：”“\'。，、？]+',
   //英文字母、数字、下划线
   ENG_NUM:'^\\w+$',
   CHN_ENG_NUM:'^[\u4E00-\u9FA5A-Za-z0-9]+$',
   //正常字符,除特殊字符以外的其他所有字符，包括其他语言  %&+
   NORMAL_REG1:'^[^"\'<>%;)(&+}{#;=$]+$',//'^[\u4E00-\u9FA5A-Za-z0-9 ()（）*-_]+$'
   NORMAL_REG:'^[^$]+$',//'^[\u4E00-\u9FA5A-Za-z0-9 ()（）*-_]+$'
   TEL_NUMBER:'^[0-9 ()+]+$' //加号，括号，空格和数字
 }
 //校验不合格提示
 validatorTip = {
    maxLenth(len){
      return "最大长度不允许大于"+len+"!"
    },
   tip_special:"不允许输入特殊字符！"
 }
  private aCity: object = {
    11: '北京', 12: '天津', 13: '河北', 14: '山西',
    15: '内蒙古', 21: '辽宁', 22: '吉林',
    23: '黑龙江', 31: '上海', 32: '江苏',
    33: '浙江', 34: '安徽', 35: '福建',
    36: '江西', 37: '山东', 41: '河南', 42: '湖北', 43: '湖南',
    44: '广东', 45: '广西', 46: '海南', 50: '重庆', 51: '四川',
    52: '贵州', 53: '云南', 54: '西藏', 61: '陕西', 62: '甘肃',
    63: '青海', 64: '宁夏', 65: '新疆', 71: '台湾', 81: '香港',
    82: '澳门', 91: '国外'
  };

  private TIMER = 2000;

  initBtnShow(topLevel, secondLevel, btnKey) {
    if (!storage.get('menu')) {
      return {};
    }
    const menu = eval(storage.get('menu'));
    let jurisdiction = [], myBtn: any;
    for (let i = 0; i < menu.length; i++) {
      if (menu[i].text === SysData['level_top_array'][topLevel]) {
        const child = menu[i].children;
        for (let j = 0; j < child.length; j++) {
          if (child[j].text === SysData['level_sec_array'][topLevel][secondLevel]) {
            jurisdiction = child[j].children;
          }
        }
      }
    }

    const backTarget = {};
    myBtn = SysData[btnKey];
    for (let i = 0; i < jurisdiction.length; i++) {
      backTarget[jurisdiction[i].text] = jurisdiction[i].checked;
    }

    for (const key of myBtn) {
      if (backTarget[key['key']] === undefined) {
        backTarget[key['key']] = false;
      }
    }

    for (const key in backTarget) {
      backTarget[key] = !backTarget[key];
    }

    return backTarget;
  }

  // 身份证校验
  isCardID(sId) {
    let iSum = 0;
    const info = '';
    if (!/^\d{17}(\d|x)$/i.test(sId)) {
      return '你输入的身份证长度或格式错误';
    }
    sId = sId.replace(/x$/i, 'a');
    if (this.aCity[parseInt(sId.substr(0, 2), 10)] == null) {
      return '你的身份证地区非法';
    }
    const sBirthday = sId.substr(6, 4) + '-' + Number(sId.substr(10, 2)) + '-' + Number(sId.substr(12, 2));
    const d = new Date(sBirthday.replace(/-/g, '/'));
    if (sBirthday !== (d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate())) {
      return '身份证上的出生日期非法';
    }
    for (let i = 17; i >= 0; i--) {
      iSum += (Math.pow(2, i) % 11) * parseInt(sId.charAt(17 - i), 11);
    }
    if (iSum % 11 !== 1) {
      return '你输入的身份证号非法';
    }
    return true;
  }

  loading(flag) {
    const html = `<div class="loading">
     <img src="/assets/images/loading.jpg">
   </div>`;
    if (flag) {
      $('.smart-container').append(html);
    } else {
      $('.loading').remove();
    }
  }

  tips(msgTitle: string, msgDetail: string = '', msgType: any = 'success', timer: number = this.TIMER) {
    /*setTimeout(() => {
      new swal({
        title: msgTitle,
        text: msgDetail,
        type: msgType,
        timer: timer,
        showConfirmButton: false,
        showCancelButton: true,
        cancelButtonText: '确定'
      });
    }, 50);*/


  }


  tipsConfirm(msgTitle: string, msgText: string, msgType: any = 'success', callback) {
    /*new swal({
      title: msgTitle,
      text: msgText,
      type: msgType,
      showCancelButton: true,
      confirmButtonColor: '#3085d6',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      // confirmButtonClass: 'btn btn-success swal-confirm-b',
      // cancelButtonClass: 'btn btn-danger',
      // buttonsStyling: false
    }, (isConfirm) => {
      if (isConfirm) {
        callback();
      }
    });*/
  }

  // 手机号码的正确检查
  checkMobile(phoneNum) {
    const reg = /^[0-9]{3,20}$/; // 验证规则
    const flag = reg.test(phoneNum); // true
    return flag;
  }
  //table页面，每页展示的条数，n等于除tbody之外的其它所有高度之和；
  pageSize(n){
    if ((document.body) && (document.body.clientHeight)){
        return Math.round((document.body.clientHeight - n)/40);
    }
    else if ((document.documentElement) && (document.documentElement.clientHeight)) {
       return Math.round((document.documentElement.clientHeight - n)/40);  //n=250
    }
  }
  // 能输入数字和小数点的判断
  numberFixed(target: any) {
    const newH = target.replace(/[^\d\.]*/g, '');
    if (String(newH).split('.').length > 2) {
      target = target.substr(0, target.length - 1);
    }
    if (String(newH).substr(-1, 1) !== '.') {
      const tmp = String(parseFloat(newH).toFixed(1));
      const p = parseFloat(tmp);
      target = p;
    }
    return target;

  }
    //保留小数点位数
    initNumber(target:any,num){
        let str=target.toString();
        if(str.indexOf('.')>-1){
            let arr=str.split('.');
            if(arr[1].length > num){
                arr[1]=arr[1].substr(0,num);
                target=Number(arr.join('.'));
            }
        }
        return target;
    }
  //md5加密
 // strMD5(str){
  //  return Md5.hashStr(str);
  //}
    //转换两个日期区间
    covertRange(data0,data1){
        let Month0=data0.getMonth()+1;
        let Month1=data1.getMonth()+1;
        let Day0=data0.getDate();
        let Day1=data1.getDate();
        if(Month0<10){
            Month0=`0${Month0}`;
        }
        if(Month1<10){
            Month1=`0${Month1}`;
        }
        if(Day0<10){
            Day0=`0${Day0}`;
        }
        if(Day1<10){
            Day1=`0${Day1}`;
        }  
        return [`${data0.getFullYear()}-${Month0}-${Day0}`,`${data1.getFullYear()}-${Month1}-${Day1}`];    
    }  
  //获取当前时间并格式化 2018-12-18 16:56:31
  getNowFormatDate() {
    var date = new Date();
    var seperator1 = "-";
    var seperator2 = ":";
    var month = date.getMonth() + 1;
    var strDate = date.getDate();
    var mon1 = "";
    var strDt = "";
    var strH = "";
    var strMin = "";
    var strSed = "";
    if (month >= 1 && month <= 9) {
      mon1 = "0" + month;
    }else{
      mon1 = month+"";
    }
    if (strDate >= 0 && strDate <= 9) {
      strDt = "0" + strDate;
    }else{
      strDt = strDate+""
    }
    if(date.getHours() >=0 && date.getHours() <=9){
      strH = "0"+date.getHours();
    }else{
      strH = date.getHours()+"";
    }
    if(date.getMinutes() >=0 && date.getMinutes() <=9){
      strMin = "0"+date.getMinutes();
    }else{
      strMin = date.getMinutes()+"";
    }
    if(date.getSeconds() >=0 && date.getSeconds() <=9){
      strSed = "0"+date.getSeconds();
    }else{
      strSed = date.getSeconds()+"";
    }
    var currentdate = date.getFullYear() + seperator1 + mon1 + seperator1 + strDt
      + " " + strH + seperator2 + strMin
      + seperator2 + strSed;
    return currentdate;
  }
  //获取时间格式为 2018_12_10_12_00_00
  getNowFormatDate_underline(date:Date) {
    var seperator = "_";
    var month = date.getMonth() + 1;
    var strDate = date.getDate();
    var mon1 = "";
    var strDt = "";
    var strH = "";
    var strMin = "";
    var strSed = "";
    if (month >= 1 && month <= 9) {
      mon1 = "0" + month;
    }else{
      mon1 = month+"";
    }
    if (strDate >= 0 && strDate <= 9) {
      strDt = "0" + strDate;
    }else{
      strDt = strDate+""
    }
    if(date.getHours() >=0 && date.getHours() <=9){
      strH = "0"+date.getHours();
    }else{
      strH = date.getHours()+"";
    }
    if(date.getMinutes() >=0 && date.getMinutes() <=9){
      strMin = "0"+date.getMinutes();
    }else{
      strMin = date.getMinutes()+"";
    }
    if(date.getSeconds() >=0 && date.getSeconds() <=9){
      strSed = "0"+date.getSeconds();
    }else{
      strSed = date.getSeconds()+"";
    }
    var formateDate = date.getFullYear() + seperator + mon1 + seperator + strDt +
    seperator + strH + seperator + strMin
      + seperator + strSed;
    return formateDate;
  }

  //获取某个时间的前/后几秒/分钟/小时/天 ，flg=1 前 flg=0 后 mss:毫秒数
  getDateFront(date:Date,flg:String,mss:number){
    var thisDate = new Date(date);
    if(flg =="1"){
      return new Date(thisDate.getTime() - mss);
    }else{
      return new Date(thisDate.getTime() + mss);
    }
  }
  //转换时间 格式：2019-12-31 05:07:45
  convertTime(date){
    let Month=date.getMonth()+1;
    let Day=date.getDate();
    let hour=date.getHours();
    let minute=date.getMinutes();
    let second=date.getSeconds();
    if(Month<10){
        Month=`0${Month}`;
    };
    if(Day<10){
        Day=`0${Day}`;
    }   
    if(hour<10){
        hour=`0${hour}`;
    }
    if(minute<10){
        minute = `0${minute}`;
    }
    if(second<10){
      second=`0${second}`;
    }
    date=`${date.getFullYear()}-${Month}-${Day} ${hour}:${minute}:${second}`;    
    return date;
  }
  convertTime2(date){
    let Month=date.getMonth()+1;
    let Day=date.getDate();
    if(Month<10){
        Month=`0${Month}`;
    };
    if(Day<10){
        Day=`0${Day}`;
    }   
    date=`${date.getFullYear()}-${Month}-${Day} 00:00:00`;    
    return date;
  }
   //比较两个日期的大小
   compareDate(date0,date1){
    let Year0=date0.getFullYear();
    let Month0=date0.getMonth()+1;
    let Day0=date0.getDate();
    let Year1=date1.getFullYear();
    let Month1=date1.getMonth()+1;
    let Day1=date1.getDate();
    if((Year0 > Year1) || (Year0==Year1&& Month0>Month1) || (Year0==Year1&& Month0==Month1&&Day0>Day1)){
        return false;
    } else {
        return true;
    }
  }
  //转换日期 格式： 2019-06-08
  convertDate(date){
    let Month=date.getMonth()+1;
    let Day=date.getDate();
    if(Month<10){
        Month=`0${Month}`;
    };
    if(Day<10){
        Day=`0${Day}`;
    }   
    date=`${date.getFullYear()}-${Month}-${Day}`;    
    return date;
  }
  //获取两个日期之间的所有日期   2019-06-08
  getBetweenDateStr (startDate, endDate) {
    const dateList = [];
    let Year0=`${new Date(startDate).getFullYear()}`;
    let Month0=`${new Date(startDate).getMonth()+1}`;
    let Day0=`${new Date(startDate).getDate()}`;
    if(Number(Month0)<10){
        Month0=`0${Month0}`;
    }
    if(Number(Day0)<10){
        Day0=`0${Day0}`;
    }
    dateList.push(`${Year0}-${Month0}-${Day0}`);
    while (true) {
        startDate.setDate(startDate.getDate() + 1)
        if (startDate.getTime() < endDate.getTime()) {
            let Year=`${new Date(startDate).getFullYear()}`;
            let Month=`${new Date(startDate).getMonth()+1}`;
            let Day=`${new Date(startDate).getDate()}`;
            if(Number(Month)<10){
                Month=`0${Month}`;
            }
            if(Number(Day)<10){
                Day=`0${Day}`;
            }
            dateList.push(`${Year}-${Month}-${Day}`);  
        } else {
            break;
        }
    }
    let Year1=`${new Date(endDate).getFullYear()}`;
    let Month1=`${new Date(endDate).getMonth()+1}`;
    let Day1=`${new Date(endDate).getDate()}`;
    if(Number(Month1)<10){
        Month1=`0${Month1}`;
    }
    if(Number(Day1)<10){
      Day1=`0${Day1}`;
    }
    dateList.push(`${Year1}-${Month1}-${Day1}`);
    console.log(Array.from(new Set(dateList)));
    return Array.from(new Set(dateList));
  }
  //验证是否数字
  checkNumner(val){
    let reg = /^[0-9]*$/;
    const flag = reg.test(val); // true
    return flag;
  }
  //验证是否时间格式
  checkDateTime(val){
    let reg = /^[1-9]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])\s+(20|21|22|23|[0-1]\d):[0-5]\d:[0-5]\d$/;
    const flag = reg.test(val); // true
    return flag;
  }
  //验证是否是价格格式
  checkPrice(val){
    let reg = /^(-?\d+)(\.\d+)?$/;
    const flag = reg.test(val); // true
    return flag;
  }
  //循环disable树形下拉框的节点
    disableTreeNode(cateList) {
        if (cateList && cateList.length) {
            for (let i = 0; i < cateList.length; i++) {
                let cate = cateList[i];
                cate['label']=cate['title'];
                if (cate.children && cate.children.length > 0) {
                    cate.isLeaf = false;
                    let children = cate.children;
                    this.disableTreeNode(children);
                } else {
                    cate.isLeaf = true;
                }
            }
        }
    }

}
export default new Tools();
